package com.zx.chatclient.netty;

import java.io.IOException;
import java.util.List;

import com.zx.chatclient.dto.IMMessage;
import com.zx.chatclient.fx.controller.ControlledStage;
import com.zx.chatclient.fx.controller.StageController;
import com.zx.chatclient.util.contants.ChatContants;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

@ChannelHandler.Sharable
public class ClientHandler extends ChannelInboundHandlerAdapter implements ControlledStage {

	private ChannelHandlerContext ctx;

	private StageController stageController;

	/**
	 * tcp链路简历成功后调用
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("成功连接服务器");
		this.ctx = ctx;
	}

	/**
	 * 发送消息
	 * 
	 * @param msg
	 * @return
	 * @throws IOException
	 */
	public boolean sendMsg(IMMessage msg) throws IOException {
		System.out.println("client:" + msg);
		ctx.channel().writeAndFlush(msg);
		return true;
	}

	/**
	 * 收到消息后调用
	 * 
	 * @throws IOException
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
		try {
			IMMessage m = (IMMessage) msg;
			if (ChatContants.MSGTYPE_LOGIN.equals(m.getMsgType())) {
				if (m.getResult()) {
					Client.setFriendList(m.getFriends());
					Client.setUser(m.getSender());
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							stageController.loadStage(ChatContants.FRIEND_VIEW_ID, ChatContants.FRIEND_VIEW_RES);
							stageController.setStage(ChatContants.FRIEND_VIEW_ID, ChatContants.LOGIN_VIEW_ID);
						}
					});
				} else {
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							Stage stage = stageController.getStage(ChatContants.LOGIN_VIEW_ID);
							AnchorPane anchorPane = (AnchorPane) stage.getScene().getRoot();
							List<Node> nodeList = anchorPane.getChildren();
							for (Node node : nodeList) {
								if ("msgLabel".equals(node.getId())) {
									Label msgLabel = (Label) node;
									msgLabel.setText(m.getMsg());
									break;
								}
							}
						}
					});
				}
			} else {
				Platform.runLater(new Runnable() {
					@Override
					public void run() {
						Stage stage = stageController.getStage(m.getSender().getUid());
						AnchorPane anchorPane = (AnchorPane) stage.getScene().getRoot();
						List<Node> nodeList = anchorPane.getChildren();
						for (Node node : nodeList) {
							if ("msgText".equals(node.getId())) {
								TextArea msgText = (TextArea) node;
								if (ChatContants.MSGTYPE_OFFINE.equals(m.getMsgType())) {
									if (msgText.getText() == null) {
										msgText.setText(m.getMsg() + "\n");
									} else {
										msgText.setText(msgText.getText() + m.getMsg() + "\n");
									}
								} else {
									if (msgText.getText() == null) {
										msgText.setText(m.getSender().getUname() + ":" + m.getMsg() + "\n");
									} else {
										msgText.setText(msgText.getText() + m.getSender().getUname() + ":" + m.getMsg() + "\n");
									}
								}
								break;
							}
						}
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发生异常时调用
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.err.println("与服务器断开连接:" + cause.getMessage());
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void setStageController(StageController stageController) {
		this.stageController = stageController;
	}
}